package com.guyu.common.core.util;

import org.dromara.hutool.core.lang.Singleton;
import org.dromara.hutool.http.HttpUtil;
import org.dromara.hutool.http.client.ClientConfig;
import org.dromara.hutool.http.client.Request;
import org.dromara.hutool.http.client.Response;
import org.dromara.hutool.http.client.engine.ClientEngine;
import org.dromara.hutool.http.client.engine.ClientEngineFactory;
import org.dromara.hutool.http.meta.Method;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * <p> Http请求工具类 </p>
 */
public class GyHttpUtils {
    /**
     * 获得单例的ClientEngine
     *
     * @return 单例的ClientEngine
     */
    public static ClientEngine getDefaultClient() {
        return Singleton.get(ClientEngine.class.getName(), () -> {
            ClientConfig clientConfig = new ClientConfig();
            clientConfig.setTimeout(10000);
            return ClientEngineFactory.createEngine(clientConfig);
        });
    }

    public static Response send(final Request request) {
        return getDefaultClient().send(request);
    }

    /**
     * GET表单提交
     * 将表单数据加到URL中
     */
    public static String get(final String urlString, final Map<String, Object> paramMap) {
        String url = HttpUtil.urlWithFormUrlEncoded(urlString, paramMap, Charset.defaultCharset());
        return send(Request.of(url)).bodyStr();
    }

    /**
     * GET表单提交
     * 将表单数据加到URL中
     */
    public static String get(final String urlString, final Map<String, Object> paramMap, final Map<String, String> headerMap) {
        String url = HttpUtil.urlWithFormUrlEncoded(urlString, paramMap, Charset.defaultCharset());
        return send(Request.of(url).header(headerMap)).bodyStr();
    }

    /**
     * GET请求的表单提交
     */
    public static String form(final String urlString, final Map<String, Object> paramMap) {
        return send(Request.of(urlString).form(paramMap)).bodyStr();
    }

    /**
     * GET请求的表单提交
     */
    public static String form(final String urlString, final Map<String, Object> paramMap, final Map<String, String> headerMap) {
        return send(Request.of(urlString).header(headerMap).form(paramMap)).bodyStr();
    }

    public static String post(final String urlString, final String body) {
        return send(Request.of(urlString).method(Method.POST).body(body)).bodyStr();
    }

    public static String post(final String urlString, final String body, final Map<String, String> headerMap) {
        return send(Request.of(urlString).method(Method.POST).header(headerMap).body(body)).bodyStr();
    }

    public static String post(final String urlString, final Map<String, Object> paramMap) {
        return send(Request.of(urlString).method(Method.POST).form(paramMap)).bodyStr();
    }

    public static String post(final String urlString, final Map<String, Object> paramMap, final Map<String, String> headerMap) {
        return send(Request.of(urlString).method(Method.POST).header(headerMap).form(paramMap)).bodyStr();
    }


}
